//
//  MeterViewController.m
//  Teximeter
//
//  Created by BEA DONG HWAN on 11. 2. 5..
//  Copyright 2011 Ajou University. All rights reserved.
//

#import "MeterViewController.h"
#import "TrackMapViewController.h"
#import "Teximeter_coreAppDelegate.h"
#import "GPSModel.h"
#import "InformationViewController.h"
#import "SharedDBManager.h"
#import "track.h"
#import "OptionValueManager.h"

@implementation MeterViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	
//	[[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
//	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
	
	locationManager=[[CLLocationManager alloc] init];
	locationManager.delegate=self;
	locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
	
	
	[endButton setEnabled:NO];
	[trackButton setEnabled:NO];
	[startButton setEnabled:YES];
	
	numberLine = [[NumberLineView alloc]initWithFrame:CGRectMake(40, 132, 400, 70)];
	[self.view addSubview:numberLine];
	[numberLine setNumber:0];
	[self.view setBackgroundColor:[UIColor blackColor]];
	isMidinght = NO;
	isStarted = NO;
	beforeLati = -1;
	initCount = 0;
	
	sharedDB = [SharedDBManager sharedInstance];
	oldTimeArray = [[NSMutableArray alloc]init];
	costTimeArray = [[NSMutableArray alloc]init];
	
	[debugView setHidden:YES];
	
	[self.view addSubview:cover];
	[cover setHidden:YES];
	
	
	
	//UIImageView * testAnimation = [[UIImageView alloc] initWithFrame:CGRectMake(120,160,320,40)];
	runningImage.animationImages = [[NSMutableArray alloc] initWithObjects:	
									 [UIImage imageNamed:@"pic1.png"],
									 [UIImage imageNamed:@"pic2.png"],
									 [UIImage imageNamed:@"pic3.png"],
									 [UIImage imageNamed:@"pic4.png"], nil];
	
	
	
	


}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)rotateMainCircleLogo:(float)value {
	
//	CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
//	rotate.fromValue = [NSNumber numberWithFloat:(0.0f * M_PI / 180.0f)];
//	rotate.toValue = [NSNumber numberWithFloat:(360.0f * M_PI / 180.0f)];
//	rotate.removedOnCompletion = NO;
//	rotate.speed = value/19.0f;
//	rotate.duration = 0.95f;
//	rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
//	rotate.delegate = self;
//	
//	[runningImage.layer addAnimation:rotate forKey:nil];
	
	runningImage.animationDuration = value;
	runningImage.animationRepeatCount = 1;
	[runningImage startAnimating];	
}


-(IBAction)clickMore
{
	
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:@"Menu Size Up" context:context];
	[UIView setAnimationDuration:0.7f];
	[UIView setAnimationDelegate:nil];
	[UIView setAnimationDidStopSelector:nil];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

	CGRect targetRect = moreView.frame;
	if(moreView.frame.origin.x <0)
	{
		targetRect.origin.x = 0;
		
	}
	else {
		targetRect.origin.x = -480+50;
	}
	
	[moreView setFrame:targetRect];
	[UIView commitAnimations];

}

-(IBAction)clickInfor
{
	
	InformationViewController* controller = [[InformationViewController alloc]init];
	[self presentModalViewController:controller animated:YES];
	[controller release];
	
//	if([debugView isHidden])
//	{
//		[debugView setHidden:NO];
//		[self.view bringSubviewToFront:debugView];
//	}
//	else {
//		[debugView setHidden:YES];
//	}
}
-(IBAction)clickNight
{
	if(isMidinght)
	{
		isMidinght = NO;
		[nightImage setImage:[UIImage imageNamed:@"icon_night.png"]];
		[nightImage setAlpha:0.6f];
	}
	else {
		isMidinght = YES;
		[nightImage setImage:[UIImage imageNamed:@"icon_night_ov.png"]];
		[nightImage setAlpha:1.0f];
	}
	
	if(!isStarted)
	{
		if(isMidinght)
		{
			baseCost = 2400*1.2f;
		}
		else {
			baseCost = 2400.0f;
		}
		totalCost = baseCost;
	}
	[numberLine setNumber:totalCost];

}

-(IBAction)showTrack
{
	TrackMapViewController* controller = [[TrackMapViewController alloc]init];
	[self presentModalViewController:controller animated:YES];
	[controller release];
}


-(IBAction)clickStart
{
	isStarted = YES;
	locationManager.delegate = self;
	[locationManager startUpdatingLocation];
	[endButton setEnabled:YES];
	[trackButton setEnabled:NO];
	[startButton setEnabled:NO];
	[self initData];
	[numberLine setNumber:totalCost];
	timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getData:) userInfo:nil repeats:YES];
	[cover setHidden:NO];
	
}

-(IBAction)clickEnd
{
	isStarted = NO;
	[timer invalidate];
	[locationManager stopUpdatingLocation];
	locationManager.delegate = nil;
	
	[endButton setEnabled:NO];
	[trackButton setEnabled:YES];
	[startButton setEnabled:YES];
	
}

-(IBAction)clickTemp
{
	[debugView resignFirstResponder];
}


-(void)debugMessage:(NSString*)value
{
	NSMutableString* message =[[NSMutableString alloc]initWithFormat:@"%@\n%@",debugView.text,value];
	debugView.text = message;
	[message release];
}


-(void)getData:(NSTimer*)sender
{
	
	if(speed<0)
	{
		speed =0;
	}
	
	
	
	//총 시간
	NSDate* now = [NSDate date];
	NSDate* old = [costTimeArray objectAtIndex:0];
	double diffrence = [now timeIntervalSinceDate:old];
	
	[costTimeArray removeAllObjects];
	[costTimeArray addObject:now];
	
	totalTime+=diffrence;
	
	
	if(speed*3.6f<=15.0f)
	{
		basicTimeCheck+=diffrence;
	}
	
	
	double checkBasic = totalDistance + basicTimeCheck*4.16666f;
	//기본 요금 구간을 지났는지 확인하는 부분
	if(checkBasic > 2000.0f)
	{
		isOverBasic  = YES;
	}
	
	//기본요금 구간을 지났으면 거리요금인지 시간요금인지를 구별하여 요금을 부과한다.
	if(isOverBasic)
	{
		if(speed*3.6f>14.81)
		{
			//거리 요금 거리
			[currentWay setText:@"거리요금"];
		}
		else 
		{
			//시간요금일 경우 비용 시간을 추가시킨다.
			[currentWay setText:@"거리요금+시간요금"];
			costTime+=diffrence;			
		}		
		
	}
	else 
	{
		if(speed*3.6f>14.81)
		{
			//거리 요금 거리
			[currentWay setText:@"기본요금"];
		}
		else 
		{
			//시간요금일 경우 비용 시간을 추가시킨다.
			[currentWay setText:@"기본요금+시간요금"];
			
		}	
		
	}
	
	
	
	
	//택시비 총 요금 계산 하는 구간
	if(isMidinght)
	{
		totalCost = baseCost + (int)(costDistance/144.0f)*100*1.2 + (int)(costTime/35)*100*1.2;
	}
	else {
		totalCost = baseCost + (int)(costDistance/144.0f)*100 + (int)(costTime/35)*100;
	}

	
	//회전 하는 것 보여주는 것
	if(speed <=0)
	{
		[self rotateMainCircleLogo:15.0f/3.6f];
	}
	else {
		[self rotateMainCircleLogo:15.0f/3.6f+speed];
	}

	//화면에 뿌려주는 구간
	[timeLabel setText:[NSString stringWithFormat:@"%@",now]];
	[totalTimeLabel setText:[NSString stringWithFormat:@"%.0f 초",totalTime]];
	[costTimeLabel setText:[NSString stringWithFormat:@"%.0f 초",costTime]];
	[totalDistanceLabel setText:[NSString stringWithFormat:@"%.2f m",totalDistance]];
	[costDistanceLabel setText:[NSString stringWithFormat:@"%.2f m",costDistance]];
	[currentLati setText:[NSString stringWithFormat:@"%.3f",disLati]];
	[currentLongi setText:[NSString stringWithFormat:@"%.3f",disLong]];
	[velocityLabel setText:[NSString stringWithFormat:@"%.0f km/h",speed*3.6]];
	[numberLine setNumber:totalCost];
	
	[loadingPercent setText:[NSString stringWithFormat:@"%.0f %%",((float)initCount)/9.0f*100.0f]];
	
	
	if(initCount > 9)
	{
		
		[cover setHidden:YES];
	}
	else {
		
		invalidCount+=diffrence;
	}

	if(totalTime >30 && ![cover isHidden])
	{
		if(!signalChecked)
		{
			signalChecked = YES;
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"GPS 업데이트 주기" message:[NSString stringWithFormat:@"GPS 신호 업데이트 주기가 %.1f(회/초) 입니다.",initCount/totalTime] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			alert.tag = 2;
			[alert show];
			[alert release];
		}
//		[self clickEnd];
		
	}
}


//확인을 누르면 뒤로 돌아간다.
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[cover setHidden:YES];
}





	 
	 
-(void)initData
{
	[sharedDB deleteAllAddress];
	[OptionValueManager setIndexNumber:0];
	totalTime = 0;
	totalDistance =0;
	initCount = 0;
	costTime = 0;
	costDistance = 0;
	isOverBasic = NO;
	signalChecked = NO;
	
	beforeLati = -1;
	basicTimeCheck =0;
	trustGPS = 0;

	if(isMidinght)
	{
		baseCost = 2400.0*1.2f;
	}
	else {
		baseCost = 2400.0;
	}
	[costTimeArray removeAllObjects];
	[costTimeArray addObject:[NSDate date]];
	totalCost = baseCost;
	
	invalidCount = 0;
	valideCount = 0;
}
	 


- (void)scheduleAlarmForDate:(NSDate*)theDate
{
    UIApplication* app = [UIApplication sharedApplication];
    NSArray*    oldNotifications = [app scheduledLocalNotifications];
	
    // Clear out the old notification before scheduling a new one.
    if ([oldNotifications count] > 0)
        [app cancelAllLocalNotifications];
	
    // Create a new notification
    UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease];
    if (alarm)
    {
        alarm.fireDate = theDate;
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.soundName = @"alarmsound.caf";
        alarm.alertBody = @"Time to wake up!";
		
        [app scheduleLocalNotification:alarm];
    }
}


#pragma mark Location delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	
	CLLocationCoordinate2D newMyLocation = newLocation.coordinate;
	
	if([oldTimeArray count]==0)
	{
		[oldTimeArray addObject:newLocation.timestamp];
	}
	
	//Set Zoom level using Span
	disLati  = newMyLocation.latitude;
	disLong = newMyLocation.longitude;
	timeStamp = newLocation.timestamp;
	speed  = newLocation.speed;
	
	
	double temp = [timeStamp timeIntervalSinceDate:[oldTimeArray objectAtIndex:0]];
	
	double tempTime = [timeStamp timeIntervalSinceDate:oldLocation.timestamp];
	tempDistance = [newLocation distanceFromLocation:oldLocation];
	NSLog(@"tempTime = %f",tempTime);
	
	if(temp > totalTime || tempTime >totalTime)
	{
		[oldTimeArray removeAllObjects];
		[oldTimeArray addObject:newLocation.timestamp];
		return;
	}
	
	
	
	
	
//[self debugMessage:[NSString stringWithFormat:@"accuracy = %f",newLocation.horizontalAccuracy]];
//	[self debugMessage:[NSString stringWithFormat:@"1 %d,speed:%f time:%f,distance:%f",initCount,speed,temp,tempDistance]];
	if(speed <=0 && tempDistance !=0)
	{
		//거리는 있는데 시간오류로 인해 속도 에러 발생시 속도를 보정해 준다. 이때 마지막 유효시간이 
		speed = tempDistance/temp;
	}
	
//	[self debugMessage:[NSString stringWithFormat:@"2 %d,speed:%f time:%f,distance:%f",initCount,speed,temp,tempDistance]]; 
//	[timeLabel setText:[NSString stringWithFormat:@"%@",newLocation.timestamp]];
	
	if(initCount>8)
	{
		
		if(speed<60.0f)
		{
			totalDistance+=tempDistance;
		}
		else 
		{
			invalidCount+=temp;
		}
		
		
		if(isOverBasic)
		{
			//거리 요금 거리
			costDistance+=tempDistance;
			if(speed*3.6f<=15.0f)
			{
				

			}
		}
		
		if(tempDistance>0)
		{
			[oldTimeArray removeAllObjects];
			[oldTimeArray addObject:newLocation.timestamp];
			//디비에 기록한다.
			track* aData = [sharedDB getDataInstance];
			[aData setLatitude:[NSNumber numberWithDouble:disLati]];
			[aData setLongitude:[NSNumber numberWithDouble:disLong]];
			[aData setTime:newLocation.timestamp];
			[sharedDB saveDataInstance:aData];
		}
		
		if(tempTime<3.0f)
		{
			valideCount+=tempTime;
		}
		else 
		{
			invalidCount+=tempTime;
		}
	}
	
	
	
	initCount++;
	if(valideCount>0 | invalidCount>0)
	{
		trustGPS = valideCount/(valideCount+invalidCount)*97.0f;
	}
	
	
	[validCountLabel setText:[NSString stringWithFormat:@"%.2f%%",trustGPS]];
	
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	
}



- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
